const User = require("../models/user");
const jwt = require("jsonwebtoken");
const { JWT_SECRET, JWT_EXPIRES_IN } = require("../config/constants");

class UserController {
  // 用户登录
  static async login(req, res) {
    try {
      const { username, password } = req.body;
      const user = await User.findByUsername(username);

      if (!user) {
        return res
          .status(401)
          .json({ success: false, message: "用户名或密码错误" });
      }

      const isValidPassword = await User.verifyPassword(
        password,
        user.password
      );
      if (!isValidPassword) {
        return res
          .status(401)
          .json({ success: false, message: "用户名或密码错误" });
      }

      if (user.status !== 1) {
        return res
          .status(403)
          .json({ success: false, message: "账号已被禁用" });
      }

      const token = jwt.sign(
        { id: user.id, username: user.username, role: user.role },
        JWT_SECRET,
        { expiresIn: JWT_EXPIRES_IN }
      );

      res.json({
        success: true,
        data: {
          token,
          user: {
            id: user.id,
            username: user.username,
            role: user.role,
          },
        },
      });
    } catch (error) {
      console.error("Login error:", error);
      res.status(500).json({ success: false, message: "登录失败" });
    }
  }

  // 获取当前用户信息
  static async getCurrentUser(req, res) {
    try {
      const user = await User.findById(req.user.id);
      if (!user) {
        return res.status(404).json({ success: false, message: "用户不存在" });
      }
      res.json({
        success: true,
        data: {
          id: user.id,
          username: user.username,
          role: user.role,
        },
      });
    } catch (error) {
      console.error("Get current user error:", error);
      res.status(500).json({ success: false, message: "获取用户信息失败" });
    }
  }

  // 创建用户
  static async createUser(req, res) {
    try {
      const { username, password, role } = req.body;
      const existingUser = await User.findByUsername(username);
      if (existingUser) {
        return res
          .status(400)
          .json({ success: false, message: "用户名已存在" });
      }
      const userId = await User.create({ username, password, role });
      res.status(201).json({ success: true, data: { id: userId } });
    } catch (error) {
      console.error("Create user error:", error);
      res.status(500).json({ success: false, message: "创建用户失败" });
    }
  }

  // 更新用户
  static async updateUser(req, res) {
    try {
      const { id } = req.params;
      const userData = req.body;
      const success = await User.update(id, userData);
      if (!success) {
        return res.status(404).json({ success: false, message: "用户不存在" });
      }
      res.json({ success: true, message: "更新成功" });
    } catch (error) {
      console.error("Update user error:", error);
      res.status(500).json({ success: false, message: "更新用户失败" });
    }
  }

  // 删除用户
  static async deleteUser(req, res) {
    try {
      const { id } = req.params;
      const success = await User.delete(id);
      if (!success) {
        return res.status(404).json({ success: false, message: "用户不存在" });
      }
      res.json({ success: true, message: "删除成功" });
    } catch (error) {
      console.error("Delete user error:", error);
      res.status(500).json({ success: false, message: "删除用户失败" });
    }
  }
}

module.exports = UserController;
